package cn.rongdao.jrkabao.base;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.mifengkong.frtools.util.FRToast;
import com.mifengkong.frtools.util.PictureUtil;
import com.mifengkong.frwidget.dialog.FRDialog;
import com.mifengkong.frwidget.dialog.FRDialogClickListener;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;

import java.util.List;

import cn.mifengkong.appcommon.customecamera.CameraActivity;
import cn.rongdao.jrkabao.R;
import cn.rongdao.jrkabao.util.permission.GoToPermissionSetting;

/**
 * Created by jiangyongxing on 2017/4/17.
 * 描述：
 */

public abstract class FRBaseTakePhotoActivity extends BaseAutoFinishActivity {

    /***
     * 使用照相机拍照获取图片
     */
    public static final int SELECT_PIC_BY_TACK_PHOTO = 1;
    /***
     * 使用相册中的图片
     */
    public static final int SELECT_PIC_BY_PICK_PHOTO = 2;
    /**
     * 只拍摄身份证，不包含人的,正面，头像那边
     */
    public static final int PIC_WITHOUT_PERSON_FRONT = 3;
    /**
     * 只拍摄身份证，不包含人的,反面
     */
    public static final int PIC_WITHOUT_PERSON_OPPOSITE = 4;
    /**
     * 人手持身份证的
     */
    public static final int PIC_WITH_PERSON = 5;

    /**
     * OCR照片
     */
    public static final int REQUEST_CODE_CAMERA = 102;


    private Intent mIntent;
    public int picType = 0;//拍照的类型，是拍身份证的还是手持身份证的,这边需要知道用户是想拍哪张照片是为了在自定义相机里面展示不同的框
    private Uri mPhotoUri;
    private String mPicPath;
    private String mSuffix;
    private boolean useCustomerCarema;//是否开启自定义的相机
    protected boolean isHavePermission = false;
    protected FRDialog caremaOptionsDialog;
    protected int mAlbumStatus;

    @Override
    protected void initView() {
        checkPermission();
        initCaremaRemindDialog();
    }

    private void checkPermission() {
        AndPermission.with(this)
                .requestCode(100)
                .permission(Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE)
                .callback(new PermissionListener() {
                    @Override
                    public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                        isHavePermission = true;
                    }

                    @Override
                    public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                        isHavePermission = false;
                    }
                }).start();
    }

    /**
     * 打开相机，拍摄照片
     *
     * @param useCustomerCarema 是否使用自定义相机
     */
    public void takePhoto(boolean useCustomerCarema, int picType) {
        this.useCustomerCarema = useCustomerCarema;
        this.picType = picType;
        //执行拍照前，应该先判断SD卡是否存在
        String SDState = Environment.getExternalStorageState();
        if (SDState.equals(Environment.MEDIA_MOUNTED)) {
            if (useCustomerCarema) {
                openCustomerCarema();
            } else {
                openSystemCarema();
            }
        } else {
            FRToast.showToastSafe("内存卡不存在");
        }
    }

    /***
     * 从相册中取图片
     */
    protected void pickPhoto() {
        useCustomerCarema = false;
        Intent intent = new Intent(
                Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");
        startActivityForResult(intent, SELECT_PIC_BY_PICK_PHOTO);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //拍照或者是选择图片返回
        if (resultCode == Activity.RESULT_OK && requestCode != REQUEST_CODE_CAMERA) {
            if (null != data) {
                doPhoto(requestCode, data);
            }
        }
        if (requestCode == GoToPermissionSetting.REQUEST_CODE_PERMISSION_SETTING) {
            checkPermission();
        }
    }


    /**
     * 选择图片后，获取图片的路径
     *
     * @param requestCode
     * @param data
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    public void doPhoto(int requestCode, Intent data) {
        if (useCustomerCarema) {
            mPicPath = data.getStringExtra("path");
            if (TextUtils.isEmpty(mPicPath)) {
                FRToast.showToastSafe("选择图片文件出错，请重试");
                return;
            }
            if (mPicPath != null && (mPicPath.endsWith(".jpeg") || mPicPath.endsWith(".JPEG"))) {
                getPicSuffix();
            } else {
                Toast.makeText(this, "选择图片文件不正确", Toast.LENGTH_LONG).show();
            }
        } else {
            if (getSystemCaremaPhotoPath(requestCode, data)) return;
            if (mPicPath != null && PictureUtil.judgePictureType(mPicPath)) {
                getPicSuffix();
            } else {
                Toast.makeText(this, "选择图片文件不正确", Toast.LENGTH_LONG).show();
            }
        }
    }

    private void getPicSuffix() {
        //截取图片的后缀名
        String[] str = mPicPath.split("\\.");
        mSuffix = str[str.length - 1];

        successReturnPicpath(mPicPath, String.valueOf(".") + mSuffix, PictureUtil.bitmapToString(mPicPath));
    }

    private boolean getSystemCaremaPhotoPath(int requestCode, Intent data) {
        if (requestCode == SELECT_PIC_BY_PICK_PHOTO) //从相册取图片，有些手机有异常情况，请注意
        {
            if (data == null) {
                FRToast.showToastSafe("选择图片文件出错，请重试");
                return true;
            }

            try {
                mPhotoUri = getUri(data);
            } catch (Exception e) {
                //兼容小米手机。所以不选择这种方法
                mPhotoUri = data.getData();
            }
            if (mPhotoUri == null) {
                FRToast.showToastSafe("选择图片文件出错，请重试");
                return true;
            }
        }
        String[] pojo = {MediaStore.Images.Media.DATA};
        if (pojo == null) {
            FRToast.showToastSafe("选择图片文件出错，请重试");
            return true;
        }
        Cursor cursor = getContentResolver().query(mPhotoUri, pojo, null, null, null);
        if (cursor != null) {
            int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
            cursor.moveToFirst();
            mPicPath = cursor.getString(columnIndex);

        } else {
            //小米手机可能会走这个
            mPicPath = mPhotoUri.getEncodedPath();
        }
        return false;
    }

    /**
     * 返回获取到的图片地址和后缀名
     *
     * @param picPath
     * @param suffix
     */
    protected abstract void successReturnPicpath(String picPath, String suffix, String imageViewBase64);

    public void setType(int type) {
        this.picType = type;
    }

    private void openCustomerCarema() {
        if (picType == PIC_WITHOUT_PERSON_FRONT) {
            CameraActivity.start(this, picType, R.drawable.camera_aperture_front);
        } else if (picType == PIC_WITHOUT_PERSON_OPPOSITE) {
            CameraActivity.start(this, picType, R.drawable.camera_aperture_opposite);
        } else if (picType == PIC_WITH_PERSON) {
            CameraActivity.startWithFrontCamera(this, picType, R.drawable.camera_apertrue_with_person);
        }
    }

    private void openSystemCarema() {
        mIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//"android.media.action.IMAGE_CAPTURE"
        /***
         * 需要说明一下，以下操作使用照相机拍照，拍照后的图片会存放在相册中的
         * 这里使用的这种方式有一个好处就是获取的图片是拍照后的原图
         * 如果不实用ContentValues存放照片路径的话，拍照后获取的图片为缩略图不清晰
         */
        ContentValues values = new ContentValues();
        mPhotoUri = this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        mIntent.putExtra(MediaStore.EXTRA_OUTPUT, mPhotoUri);
        /**-----------------*/
        startActivityForResult(mIntent, SELECT_PIC_BY_TACK_PHOTO);
    }

    /**
     * 是否缺少权限
     *
     * @return
     */
    protected boolean lackPermission() {
        if (!isHavePermission) {
//            FRToast.showToastSafe("缺少相机或者读取存续卡权限");
            GoToPermissionSetting.showSnackBar(getActivity(), findViewById(android.R.id.content));
            return true;
        }
        return false;
    }

    public Uri getUri(android.content.Intent intent) {
        Uri uri = intent.getData();
        String type = intent.getType();
        if (uri.getScheme().equals("file") && (type.contains("image/"))) {
            String path = uri.getEncodedPath();
            if (path != null) {
                path = Uri.decode(path);
                ContentResolver cr = this.getContentResolver();
                StringBuilder sb = new StringBuilder();
                sb.append("(").append(Images.ImageColumns.DATA).append("=").append("'").append(path).append("'").append(")");
                @SuppressLint("Recycle") Cursor cur = cr.query(Images.Media.EXTERNAL_CONTENT_URI,
                        new String[]{MediaStore.Images.ImageColumns._ID},
                        sb.toString(), null, null);
                int index = 0;
                for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
                    index = cur.getColumnIndex(Images.ImageColumns._ID);
                    // set _id value
                    index = cur.getInt(index);
                }
                if (index == 0) {
                    // do nothing
                } else {
                    Uri uri_temp = Uri
                            .parse("content://media/external/images/media/"
                                    + index);
                    if (uri_temp != null) {
                        uri = uri_temp;
                    }
                }
            }
        }
        return uri;
    }

    private void initCaremaRemindDialog() {
        caremaOptionsDialog = new FRDialog.MDBuilder(thisActivity())
                .setMessage("选择获取照片方式")
                .setNegativeContentAndListener(mAlbumStatus == 1 ? "图库" : "", new FRDialogClickListener() {
                    @Override
                    public boolean onDialogClick(View view) {
                        if (mAlbumStatus == 1) {
                            pickPhoto();
                        }
                        return true;
                    }
                })
                .setNegativeTextColor(ContextCompat.getColor(thisActivity(), R.color.c333333))
                .setPositiveTextColor(ContextCompat.getColor(thisActivity(), R.color.colorPrimary))
                .setPositiveContentAndListener("相机",new FRDialogClickListener() {
                    @Override
                    public boolean onDialogClick(View view) {
                        try {
                            takePhoto(true, picType);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        return true;
                    }
                }).create();
    }
}
